<template>
	<view class="content">
		<view class="title">uniCloud</view>
		<view class="tips">
			<view>1.在cloudfunctions目录右键创建并关联服务空间</view>
			<view>2.在cloudfunctions目录内db_init.json上右键初始化云数据库</view>
			<view>3.在cloudfunctions目录右键选择“上传所有云函数”</view>
			<view>开始愉快的体验uniCloud吧！</view>
		</view>
		<view class="btn-list">
			<button type="primary" @click="add">新增一条数据</button>
			<button type="primary" @click="remove">删除一条数据</button>
			<button type="primary" @click="update">修改数据</button>
			<button type="primary" @click="get">查询前10条数据</button>
			<button type="primary" @click="useCommon">使用公用模块</button>
			<button type="primary" @click="upload">上传文件</button>
		</view>
		<view>
		  <li v-for="item in dataList" :key="item._id">
		      {{ item.name }}
		  </li>
		</view>
	</view>
</template>

<script>
	
	export default {
		data() {
			return {
				dataList:[]
			}
		},
		mounted(){
		    M.list().then(d=>this.dataList=d)
		},
		methods: {
			add() {		
				M.add({
						name: 'DCloud'+(new Date().getSeconds()),
						subType: 'uniCloud',
						createTime: Date.now()
					}).then(d=>this.get())
			},
			remove() {
				M.delete().then(d=>this.get())
			},
			update() {
			    alert("未选")
			},
			get() {
				this.M.list().then(d=>this.dataList=d)
			},
			useCommon() {
				
			},
			upload() {
				new Promise((resolve, reject) => {
					uni.chooseImage({
						chooseImage: 1,
						success: res => {
							const path = res.tempFilePaths[0]
							let ext						
							ext = res.tempFiles[0].name.split('.').pop()					
							const options = {
								filePath: path,
								cloudPath: Date.now() + '.' + ext
							}
							resolve(options)
						},
						fail: () => {
							reject(new Error('Fail_Cancel'))
						}
					})
				}).then((options) => {
					uni.showLoading({
						title: '文件上传中...'
					})
					return uniCloud.uploadFile({
						...options,
						onUploadProgress(e) {
							console.log(e)
						}
					})
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					uni.showModal({
						content: '图片上传成功，fileId为：' + res.fileID,
						showCancel: false
					})
				}).catch((err) => {
					uni.hideLoading()
					console.log(err);
					if (err.message !== 'Fail_Cancel') {
						uni.showModal({
							content: `图片上传失败，错误信息为：${err.message}`,
							showCancel: false
						})
					}
				})
			}
		}
	}
</script>

<style>
	.content {
		padding-bottom: 30px;
	}

	.title {
		font-weight: bold;
		text-align: center;
		padding: 20px 0px;
		font-size: 20px;
	}

	.tips {
		color: #999999;
		font-size: 14px;
		padding: 20px 30px;
	}

	.btn-list {
		padding: 0px 30px;
	}

	.btn-list button {
		margin-bottom: 20px;
	}

	.upload-preview {
		width: 100%;
	}
	
	
</style>
